package com.example.day11;

public class BoxDemo {
    public static void main(String[] args) {
        //临界资源
        Box box = new Box();

        Thread p1 = new P1(box);
        Thread c1 = new C1(box);

        p1.setName("p1");
        c1.setName("c1");

        p1.start();

        c1.start();
    }
}
//临界资源
class Box{
    private int content;//box中的东西

    //标记位 - 判断box中是否有东西
    boolean flag = false;//false代表木有东西

    //生产者线程 - 放
    public synchronized void setContent(int content) {
        if(flag){//有东西
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.content = content;
        //放东西了
        flag = true;
        //唤醒消费者
        notify();
    }

    //消费者线程 - 取
    public synchronized int getContent() {
        if(flag == false){ // box中没有东西
            //进入到等待阻塞的状态
            try {
                wait(); //等生产者线程唤醒它
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        flag = false;
        notify();//唤醒生产者
        return content;
    }
}
class P1 extends Thread{
    private Box box;

    private int i;

    public P1(Box box){
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName()+"-放"+(++i)+"个");
            box.setContent(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class C1 extends Thread{
    private Box box;

    public C1(Box box){
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName()+"-取"+box.getContent()+"个!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}